package com.example.storageservice.service;

import com.example.storageservice.dao.ProductMapper;
import com.example.storageservice.entity.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * program: springcloud-seata
 * description:
 * author: Mr.Yiu
 * create: 2021-05-20 17:33
 **/
@Service
public class ProductService {
    @Autowired
    ProductMapper productMapper;

    public List<Product> findProductList(){
        return productMapper.findProductList();
    }

    public Product findProduct(int productId){
        return productMapper.findProduct(productId);
    }

    @Transactional
    public Map<String, Object> deductProduct(int productId, int deductNum){
        Map<String, Object> result = new HashMap<String, Object>();
        Product p = this.findProduct(productId);
//        if(null==p){
////            result.put("code", 10);
////            result.put("desc", "产品不存在");
////            return result;
//            throw new RuntimeException("产品不存在");
//        }

        if(p.getNum()<deductNum){
//            result.put("code", 11);
//            result.put("desc", "产品库存不足");
//            return result;
            throw new RuntimeException("产品库存不足");
        }

        int i = productMapper.update(productId, deductNum);
        if(i==0){
//            result.put("code", 13);
//            result.put("desc", "扣减库存失败，操作数据库异常");
//            return result;
            throw new RuntimeException("产品库存不足");
        }else if(i==1){
            result.put("code", 1);
            result.put("desc", "扣减成功");
            return result;
        }

        return null;
    }
}
